from deepseek import function_calling
from actions import tools, available_actions
import json


class Agent:
    def __init__(self, tools):
        self.messages = []
        self.tools = tools

    def run(self, question: str):
        print(f'***问题：{question}')
        self.messages.append(
            {"role": "system", "content": "You are a helpful assistant"}
        )
        self.messages.append({"role": "user", "content": question})
        response = function_calling(self.messages, self.tools)
        if len(response.tool_calls) == 1:
            # 调用对应函数并返回结果
            function_name = response.tool_calls[0].function.name
            if not function_name:
                raise Exception(f"Invalid JSON in response: {response}")

            function_parms = response.tool_calls[0].function.arguments
            id = response.tool_calls[0].id
            params = json.loads(function_parms)
            if function_name not in available_actions:
                raise Exception(f"Unknown action: {function_name}: {function_parms}")

            # 调用Action
            print(f"***命中函数: {function_name} {function_parms}")
            action_function = available_actions[function_name]
            result = action_function(**params)
            print(f"***函数调用: {result}")
            self.messages.append(response)
            self.messages.append({"role": "tool", "tool_call_id": id, "content": f'{result}'})
            res = function_calling(self.messages, self.tools)
            print(f"***最终结果: {res.content}")


if "__main__" == __name__:
    agent = Agent(tools=tools)
    # agent.run("今天是几号呢？")
    # agent.run("告诉我今天的日期？")
    # agent.run("现在是几号")
    # agent.run("今天是周几呢？")
    # agent.run("周几呢今天？")
    # agent.run("告诉我今天是周天吗？")
    agent.run("九十九加上一？")
    agent.run("66*2？")
    agent.run("0-1？")
    agent.run("10/3？")